package com.example.petproject.controller;

import com.example.petproject.entity.vo.ReturnStatusEnum;
import com.example.petproject.entity.vo.ReturnVO;
import com.example.petproject.service.CommentPicService;
import com.example.petproject.service.third.ali.AliYunOSSService;
import jakarta.annotation.Resource;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;

/**
 * 包名称：com.example.petproject.controller
 * 类名称：FileController
 * 类描述：文件上传控制器
 * 创建人：@author DrinkMore-HotWater
 * 创建时间：2024年01月20日 13:58
 **/
@RestController
@RequestMapping("/pms/files")
public class FileController {
    @Resource
    private AliYunOSSService aliYunOSSService;
    @Resource
    private CommentPicService commentPicService;

    @PostMapping("/uploadFile")
    public ReturnVO<?> upload(MultipartFile file, Integer type, @RequestHeader(value = "Token", required = false) String token) {
        try {
            if (!StringUtils.hasText(token)) {
                return ReturnVO.error(ReturnStatusEnum.AUTH_TOKEN_EMPTY);
            }
            if (ObjectUtils.isEmpty(file)) {
                return ReturnVO.error(ReturnStatusEnum.OTHER_FILE_NOT_EMPTY_ERROR);
            }
            //调用阿里云OSS
            String filePath = aliYunOSSService.putObject(file, type);
            //文件id，在comment_pic表中插入一条图片路径的记录
            Long picId = commentPicService.addCommentPic(filePath);
            //处理响应的文件路径 -- 只能在完成图片记录新增后才能处理
            filePath=aliYunOSSService.getSymink(filePath);
            Map<String,Object> resultMap = new HashMap<>();
            resultMap.put("id",picId);
            resultMap.put("filePath",filePath);
            return ReturnVO.ok(resultMap);
        } catch (Exception e) {
            return ReturnVO.error();
        }
    }
}
